<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isEdit ? '编辑会员' : '新增会员'"
    width="600px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
    >
      <el-form-item label="姓名" prop="name">
        <el-input
          v-model="form.name"
          placeholder="请输入姓名"
          clearable
        />
      </el-form-item>
      
      <el-form-item label="手机号" prop="phone">
        <el-input
          v-model="form.phone"
          placeholder="请输入手机号"
          clearable
        />
      </el-form-item>
      
      <el-form-item label="邮箱" prop="email">
        <el-input
          v-model="form.email"
          placeholder="请输入邮箱"
          clearable
        />
      </el-form-item>
      
      <el-form-item label="性别" prop="gender">
        <el-radio-group v-model="form.gender">
          <el-radio :label="1">男</el-radio>
          <el-radio :label="2">女</el-radio>
        </el-radio-group>
      </el-form-item>
      
      <el-form-item label="生日" prop="birthday">
        <el-date-picker
          v-model="form.birthday"
          type="date"
          placeholder="请选择生日"
          value-format="YYYY-MM-DD"
          style="width: 100%"
        />
      </el-form-item>
      
      <el-form-item label="地址" prop="address">
        <el-input
          v-model="form.address"
          type="textarea"
          :rows="3"
          placeholder="请输入地址"
        />
      </el-form-item>
      
      <el-form-item label="会员等级" prop="level_id">
        <el-select
          v-model="form.level_id"
          placeholder="请选择会员等级"
          style="width: 100%"
          filterable
          clearable
        >
          <el-option
            v-for="level in levelList"
            :key="level.id"
            :label="formatLevelLabel(level)"
            :value="level.id"
          />
        </el-select>
      </el-form-item>
      
      <el-form-item v-if="isEdit" label="状态" prop="status">
        <el-radio-group v-model="form.status">
          <el-radio :label="1">启用</el-radio>
          <el-radio :label="0">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" :loading="loading" @click="handleSubmit">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, onMounted } from 'vue'
import { ElMessage, FormInstance, FormRules } from 'element-plus'
import { createMember, updateMember, getMemberDetail } from '@/api/members'
import { getMemberLevelList } from '@/api/memberLevels'
import { isMobile, isEmail } from '@/utils'

interface MemberLevel {
  id: string
  name: string
  description?: string
}

interface MemberForm {
  name: string
  phone: string
  email: string
  gender: number
  birthday: string
  address: string
  level_id: string
  status: number
}

const props = defineProps<{
  modelValue: boolean
  memberId?: string | null
}>()

const emit = defineEmits<{
  'update:modelValue': [value: boolean]
  'success': []
}>()

const formRef = ref<FormInstance | null>(null)
const loading = ref(false)
const levelList = ref<MemberLevel[]>([])

const dialogVisible = computed({
  get: () => props.modelValue,
  set: (val: boolean) => emit('update:modelValue', val)
})

const isEdit = computed(() => !!props.memberId)

// 手机号验证
const validatePhone = (_rule: any, value: string, callback: (error?: Error) => void): void => {
  if (!value) {
    callback(new Error('请输入手机号'))
  } else if (!isMobile(value)) {
    callback(new Error('请输入正确的手机号'))
  } else {
    callback()
  }
}

// 邮箱验证
const validateEmail = (_rule: any, value: string, callback: (error?: Error) => void): void => {
  if (value && !isEmail(value)) {
    callback(new Error('请输入正确的邮箱地址'))
  } else {
    callback()
  }
}

const form = reactive<MemberForm>({
  name: '',
  phone: '',
  email: '',
  gender: 1,
  birthday: '',
  address: '',
  level_id: '',
  status: 1
})

const rules: FormRules<MemberForm> = {
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { validator: validatePhone, trigger: 'blur' }
  ],
  email: [
    { validator: validateEmail, trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ]
}

// 组合显示：等级名 - 描述
const formatLevelLabel = (level: MemberLevel): string => {
  if (!level) return ''
  const name = level.name || ''
  const desc = level.description || ''
  return desc ? `${name} - ${desc}` : name
}

// 获取会员等级列表
const fetchLevelList = async (): Promise<void> => {
  try {
    const res = await getMemberLevelList({})
    if (res.code === 200 && res.data) {
      levelList.value = Array.isArray(res.data) ? res.data : (res.data.list || [])
    }
  } catch (error) {
    console.error('获取会员等级列表失败:', error)
  }
}

// 获取会员详情
const fetchMemberDetail = async (): Promise<void> => {
  if (!props.memberId) return
  
  loading.value = true
  try {
    const res = await getMemberDetail({ id: props.memberId })
    if (res.code === 200 && res.data) {
      Object.assign(form, {
        name: res.data.name || '',
        phone: res.data.phone || '',
        email: res.data.email || '',
        gender: res.data.gender || 1,
        birthday: res.data.birthday || '',
        address: res.data.address || '',
        level_id: res.data.level_id || '',
        status: res.data.status !== undefined ? res.data.status : 1
      })
    }
  } catch (error) {
    console.error('获取会员详情失败:', error)
  } finally {
    loading.value = false
  }
}

// 监听对话框打开
watch(dialogVisible, (visible: boolean): void => {
  if (visible) {
    fetchLevelList()
    if (isEdit.value) {
      fetchMemberDetail()
    } else {
      // 重置表单
      Object.assign(form, {
        name: '',
        phone: '',
        email: '',
        gender: 1,
        birthday: '',
        address: '',
        level_id: '',
        status: 1
      })
      if (formRef.value) {
        formRef.value.clearValidate()
      }
    }
  }
})

const handleClose = (): void => {
  dialogVisible.value = false
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

const handleSubmit = async (): Promise<void> => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      loading.value = true
      try {
        const data: any = { ...form }
        if (isEdit.value && props.memberId) {
          data.id = props.memberId
          await updateMember(data)
          ElMessage.success('更新成功')
        } else {
          await createMember(data)
          ElMessage.success('创建成功')
        }
        
        emit('success')
        handleClose()
      } catch (error) {
        console.error('保存会员失败:', error)
      } finally {
        loading.value = false
      }
    }
  })
}

onMounted((): void => {
  fetchLevelList()
})
</script>

<style lang="scss" scoped>
.dialog-footer {
  text-align: right;
}
</style>

